import React, {memo, useEffect, useRef, useState} from "react";
import {Dropdown, Menu, message} from "antd";
import {useSelector} from "react-redux";
import Title from "../../../../components/Title/Title";
import {MENU_STYLE, SAMPLE_TASK} from "../config";
import {deepClone, generateUUID, getRandomColor} from "../../../../common/utils";
import {useDebounce} from "../../../../common/myHooks";
import {WELL_TYPE} from "../../store/constants";

export default memo(function PlateSamples(props) {
    const {isCN} = useSelector(state => ({
      isCN: state.languageReducer.isCN
    }));
    const {wells, setWells, sample, setSample, changeWellsCounter, setShowSampleLibrary, data, wellsId, setWellsId} = props;
    const sampleColorInput = useRef();  //  sample颜色选择器
    const [sampleIndex, setSampleIndex] = useState(0);  //  选择的sample的索引
    const task = [
      {name: WELL_TYPE.UNK, color: "#00B7FA"},
      {name: WELL_TYPE.NTC, color: "#FF992B"},
      {name: WELL_TYPE.POS, color: "#FF2720"},
      {name: WELL_TYPE.NEG, color: "#FF41FF"},
      {name: WELL_TYPE.NRT, color: "#97AAFF"},
      {name: WELL_TYPE.STD, color: "#32C243"}]; //  sample task
    let cloneWells = [];
    let cloneSample = [];

    //  选择Sample后的操作
    function selectSampleOperation(indey) {
      cloneSample = deepClone(sample, cloneSample);
      if (!cloneSample[indey].name) {  //  没有设置name和channel
        return message.warn("Please enter sample name.");
      }
      for (let i = 0; i < cloneSample.length; i++) {
        if (i !== indey && cloneSample[i].name === cloneSample[indey].name) {  //  name重复
          cloneSample[indey].name = "";
          setSample(cloneSample);
          return message.warn("Rename the sample name.");
        }
      }
      cloneWells = deepClone(wells, cloneWells);
      if (cloneSample[indey].opt) { //  取消选中well的sample
        cloneSample[indey].opt = false;
        cloneWells.forEach(well => well.selected && well.sampleName === cloneSample[indey].name && ([well.sampleName, well.sampleColor, well.type] = ["", "", ""]));
      } else {  //  增加选中well的sample
        if (cloneWells.some(item => item.selected && item.sampleName)) {  //  well中已经有1个sample时提示不能超过1个
          return message.warn("Well can't have more than one sample.");
        }
        cloneSample[indey].opt = true;
        cloneWells.forEach(well => {
          if (well.selected) {
            well.sampleName = cloneSample[indey].name;
            well.sampleColor = cloneSample[indey].color;
            well.type = cloneSample[indey].type;
            well.sampleUuid = cloneSample[indey].uuid;
          }
        });
      }
      setSample(cloneSample);
      setWells(cloneWells);
      changeWellsCounter(cloneWells);
    }

    //  增加一个Sample
    function addSample() {
      cloneSample = deepClone(sample, cloneSample);
      cloneSample.unshift({
        uuid: generateUUID(),
        opt: false,
        color: getRandomColor(),
        comments: "",
        type: WELL_TYPE.UNK,
        name: "",
        control: false,
        id: "",
        mark: ""
      });
      setSample(cloneSample);
    }

    //  删除一个Sample
    function removeSample(indey) {
      cloneWells = deepClone(wells, cloneWells);
      cloneSample = deepClone(sample, cloneSample);
      cloneWells.forEach(well => well.sampleUuid === cloneSample[indey].uuid && ([well.sampleName, well.taskColor, well.type] = ["", "", ""]));
      cloneSample.splice(indey, 1);
      setWells(cloneWells);
      setSample(cloneSample);
      changeWellsCounter(cloneWells);
    }

    //  改变Sample Task
    function changeSamplesTask(task, indey) {
      cloneSample = deepClone(sample, cloneSample);
      cloneWells = deepClone(wells, cloneWells);
      cloneSample[indey].type = task.name;
      cloneWells.forEach(well => well.sampleName && well.sampleUuid === cloneSample[indey].uuid && (well.type = task.name));
      setSample(cloneSample);
      setWells(cloneWells);
    }

    //  显示Sample颜色板
    function showSamplesColorSetting(indey) {
      setSampleIndex(indey);
      sampleColorInput.current.click();
    }

    //  改变Sample颜色
    const changeSampleColor = useDebounce(value => {
      cloneSample = deepClone(sample, cloneSample);
      cloneSample[sampleIndex].color = value;
      setSample(cloneSample);
    }, 500);

    //  改变Sample
    function changeSample(value, indey, type) {
      cloneSample = deepClone(sample, cloneSample);
      cloneWells = deepClone(wells, cloneWells);
      cloneWells.forEach(well => well.sampleName && well.sampleUuid === cloneSample[indey].uuid && (well.sampleName = value));
      cloneSample[indey][type] = value;
      setSample(cloneSample);
      setWells(cloneWells);
    }

    function autoSample() {
      setShowSampleLibrary(true);
    }

    useEffect(() => {// TODO: 选中well时Sample表格联动
      let selectWellSampleId = document.getElementById(wellsId);
      selectWellSampleId?.scrollIntoView({
        behavior: 'smooth', //顺滑的滚动
        block: 'center', //容器上下的中间
        inline: 'center' //容器左右
      });
    }, [wellsId]);

    return (
      <div className="platePageSamples platePageOperation">
        <Title name={isCN ? "实验样品" : "Samples"} btn={isCN ? "添加" : "Add"} btnAction={addSample}
               btnLeftSample={isCN ? "自动" : "Auto"} btnLeftSampleAction={autoSample}
        />
        <ul>
          <li>{isCN ? "选项" : "Opt"}</li>
          <li>{isCN ? "名称" : "Name"}</li>
          <li>{isCN ? "颜色" : "Color"}</li>
          <li>{isCN ? "样品类型" : "Task"}</li>
          <li>{isCN ? "备注" : "Comments"}</li>
          <li>{isCN ? "删除" : "Del"}</li>
        </ul>
        <section className="scrollBarStyle">
          <input ref={sampleColorInput} type="color" style={{display: "none"}}
                 onChange={e => changeSampleColor(e.target.value)}
          />
          {
            sample.map((item, index) => (
              <ul key={item.color + index} id={item.uuid}>
                <li className={item.opt ? "selectedStyle" : ""} onClick={() => selectSampleOperation(index)}/>
                <input type="text" value={item.name} onChange={e => changeSample(e.target.value, index, "name")}/>
                <li>
                  <div style={{backgroundColor: `${item.color}`}} onClick={() => showSamplesColorSetting(index)}/>
                </li>
                <Dropdown
                  overlay={
                    <Menu>
                      {
                        task.map((item) => (
                          <Menu.Item key={item.name}>
                            <div style={{...MENU_STYLE, width: 60}} onClick={() => changeSamplesTask(item, index)}>{item.name}</div>
                          </Menu.Item>
                        ))
                      }
                    </Menu>
                  }
                  placement="bottomCenter"
                  trigger={['click']}
                >
                  <li>
                    <div style={{backgroundColor: `${SAMPLE_TASK[item.type]}`}}>{item.type}</div>
                  </li>
                </Dropdown>
                <input type="text" value={item.comments} onChange={e => changeSample(e.target.value, index, "comments")}/>
                <li onClick={() => removeSample(index)}/>
              </ul>
            ))
          }
        </section>
      </div>
    );
  }
);
